<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-budgetAmount="scope">
              <el-input-number
                style="width: 100%"
                :min="0"
                :max="99999999999"
                :precision="3"
                controls-position="right"
                v-model="formInfo.data.budgetAmount"
              ></el-input-number>
            </template>
            <template v-slot:form-openTime="scope">
              <el-date-picker
                v-model="formInfo.data.openTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm"
                format="YYYY-MM-DD HH:mm"
                placeholder="请选择开标时间"
              />
            </template>
            <template v-slot:form-biddingParameterId>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择招标参数"
                v-model="formInfo.data.biddingParameterName"
              >
                <template #append>
                  <el-icon @click="selectParameter"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip text="应标供应商"></Tooltip>
        </div>
        <div class="model-panel-body">
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-add>
              <el-button @click="add">新增行</el-button>
            </template>
            <template v-slot:filter-remove>
              <el-button @click="remove" :disabled="canRemove"
                >删除行</el-button
              >
              <span style="padding-left: 10px"
                >只能上传
                <b style="color: #f56c6c">docx / pdf / doc</b>
                格式文件且为文件白名单支持的格式，且大小不超过
                <b style="color: #f56c6c">500Mb</b></span
              >
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                v-model:query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-supplierName="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}.supplierName`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: true,
                              message: '请输入供应商名称',
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input
                      v-model="scope.row.supplierName"
                      :maxlength="64"
                    ></el-input>
                  </el-form-item>
                </template>
                <template v-slot:col-supplierContactUser="scope">
                  <el-input
                    v-model="scope.row.supplierContactUser"
                    :maxlength="32"
                  ></el-input>
                </template>
                <template v-slot:col-supplierContactUserTel="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}.supplierContactUserTel`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: false,
                              validator: proxy.$validate.cellphone,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input
                      v-model="scope.row.supplierContactUserTel"
                    ></el-input>
                  </el-form-item>
                </template>
                <template v-slot:col-biddingAmount="scope">
                  <el-input-number
                    :min="0"
                    :max="99999999999"
                    :precision="3"
                    controls-position="right"
                    v-model="scope.row.biddingAmount"
                  ></el-input-number>
                </template>
                <template v-slot:col-isSuccessBidding="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}.isSuccessBidding`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: true,
                              message: '请选择是否中标',
                              trigger: 'change',
                            },
                          ]
                        : []
                    "
                  >
                    <el-select-v2
                      v-model="scope.row.isSuccessBidding"
                      :options="options"
                      size="small"
                      placeholder="选择是否中标"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-bidEvaluationScore="scope">
                  <el-input-number
                    v-model="scope.row.bidEvaluationScore"
                    controls-position="right"
                    :min="0"
                    :precision="2"
                    :max="100"
                  ></el-input-number>
                </template>
                <template v-slot:col-expertOpinion="scope">
                  <el-input
                    v-model="scope.row.expertOpinion"
                    :maxlength="128"
                  ></el-input>
                </template>
                <template v-slot:col-filePathList="scope">
                  <UploadImg
                    v-model:value.sync="scope.row.filePathList"
                    multiple
                    :isShowTip="false"
                    marginBottom="0px"
                    :key="scope.$index + new Date()"
                    :action="action"
                    :file-size="500"
                    :eleSize="40"
                    list-type="text"
                    title="投标文档"
                    :file-type="fileType"
                    :response-fn="handleResponse"
                  />
                </template>
              </PageTable>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <SelectBiddingParameter
      v-if="biddingParameterInfo.visible"
      v-model:showDialog="biddingParameterInfo.visible"
      :checkBox="false"
      :query="biddingParameterInfo.query"
      :highlightRow="true"
      :saveEmpty="true"
      @callback="biddingParameterBack"
    ></SelectBiddingParameter>
  </div>
</template>

<script setup name="biddingProjectModify">
import {
  updateProject,
  createProject,
  getProjectById,
  getProjectAll,
} from '@/api/bidding.js'
import _ from 'lodash'
import { computed, watch } from 'vue'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  orderId: {
    type: [String, Number],
  },
})
const action = ref(import.meta.env.VITE_APP_BASE_API + '/pub/uploadfile')
const fileType = ref(['docx', 'pdf', 'doc'])
const options = computed(() => {
  let arr = proxy.$store.state.permission.dict['yes_or_no'] || []
  if (arr && arr.length) {
    arr = arr.map((item) => {
      return {
        value: item.code,
        label: item.name,
      }
    })
  }
  return arr
})
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '招标编号', value: 'biddingNumber', type: 'input' },
    { label: '项目名称', value: 'name', type: 'input' },
    { label: '预算金额', value: 'budgetAmount', type: 'slot' },
    {
      label: '开标时间',
      value: 'openTime',
      type: 'slot',
    },
    { label: '开标地点', value: 'openAddress', type: 'input' },
    { label: '采购人', value: 'purchUser', type: 'input' },
    { label: '采购联系人', value: 'purchContactUser', type: 'input' },
    { label: '采购联系人电话', value: 'purchContactUserTel', type: 'input' },
    { label: '采购代理机构', value: 'purchAgency', type: 'input' },
    { label: '代理机构联系人', value: 'agencyUser', type: 'input' },
    { label: '代理机构联系人电话', value: 'agencyUserTel', type: 'input' },
    { label: '关联招标参数', value: 'biddingParameterId', type: 'slot' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    biddingNumber: [
      { required: true, message: '请输入招标编号', trigger: 'blur' },
    ],
    name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    budgetAmount: [
      { required: true, message: '请输入预算金额', trigger: 'blur' },
    ],
    purchUser: [{ required: true, message: '请输入采购人', trigger: 'blur' }],
    purchContactUserTel: [
      { validator: proxy.$validate.cellphone, trigger: 'blur' },
    ],
    agencyUserTel: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
    openTime: [
      { required: true, message: '请选择开标时间', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    biddingProjectId: props.orderId,
  },
  list: [
    { type: 'slot', value: 'add' },
    { type: 'slot', value: 'remove' },
  ],
})

// 表格相关
const tableInfo = ref({
  data: [{ isSuccessBidding: '0' }],
  selections: [],

  fieldList: [
    {
      label: '供应商名称',
      value: 'supplierName',
      type: 'slot',
    },
    {
      label: '供应商联系人',
      value: 'supplierContactUser',
      type: 'slot',
    },
    {
      label: '供应商联系人电话',
      value: 'supplierContactUserTel',
      type: 'slot',
    },
    {
      label: '投标金额',
      value: 'biddingAmount',
      type: 'slot',
      minWidth: '160px',
    },
    {
      label: '是否中标',
      value: 'isSuccessBidding',
      type: 'slot',
      minWidth: '140px',
    },
    {
      label: '评标分数',
      value: 'bidEvaluationScore',
      type: 'slot',
      minWidth: '160px',
    },
    {
      label: '专家意见',
      value: 'expertOpinion',
      type: 'slot',
    },
    {
      label: '投标文档',
      value: 'filePathList',
      type: 'slot',
      minWidth: '200px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '删除',
        event: removeRow,
        show: true,
      },
    ],
  },
})
const biddingParameterInfo = ref({
  visible: false,
  query: {
    idNotIn: '',
  },
})
const canRemove = computed(() => {
  return !tableInfo.value.selections.length
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function selectParameter() {
  biddingParameterInfo.value.visible = true
  biddingParameterInfo.value.query.idNotIn =
    formInfo.value.data.biddingParameterId || ''
}
function biddingParameterBack(data) {
  if (data && data.id) {
    formInfo.value.data.biddingParameterName = data.name
    formInfo.value.data.biddingParameterId = data.id
  } else {
    formInfo.value.data.biddingParameterName = ''
    formInfo.value.data.biddingParameterId = ''
  }
}
function add() {
  tableInfo.value.data.push({
    isSuccessBidding: '0',
  })
}
function remove() {
  tableInfo.value.data = tableInfo.value.data.filter(
    (row) => !tableInfo.value.selections.includes(row)
  )
  if (!tableInfo.value.data.length) {
    tableInfo.value.data.push({ isSuccessBidding: '0' })
  }
}

function removeRow(row, index) {
  proxy.$nextTick(() => {
    let data = proxy.$fn.deepClone(tableInfo.value.data)

    tableInfo.value.data = []
    data.splice(index, 1)
    tableInfo.value.data = data
    if (!tableInfo.value.data.length) {
      tableInfo.value.data.push({ isSuccessBidding: '0' })
    }
    console.log(data)
    proxy.$forceUpdate()
  })
}

function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let list = tableInfo.value.data.filter((item) => !item.supplierName)
    if (list.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '你还有未填写完的数据，请处理',
      })
      return
    }
    const api = props.orderId ? updateProject : createProject
    let data = formInfo.value.data
    data.mergeDetails = tableInfo.value.data
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function getMain() {
  getProjectById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
  getList()
}

function getList() {
  getProjectAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.length) {
        res.data.forEach((item) => {
          item.groupKey = item.requirementType
          item.isSuccessBidding = item.isSuccessBidding + ''
        })
      }
      tableInfo.value.data = res.data
    }
  })
}
function handleResponse(response, file) {
  return file
}
onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
  if (props.orderId) {
    getMain()
  }
})
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
</style>
